import webapp2
from google.appengine.api import users
import json
import traceback
from db.exceptions import *

import random
import string
def string_generator(size=6, chars=string.ascii_uppercase + string.digits):
	return ''.join(random.choice(chars) for x in range(size))

class MyHandler(webapp2.RequestHandler):
	
	def needAuth(self):
		return True
	
	def redirectToLogin(self):
		return False # la maggior parte degli handler sono in ajax..
	
	def safeMethod(self, method):
		user = users.get_current_user()
		params = self.getAllParametersGETInDict()
		try:
			params.update(self.getAllParametersPOSTInDict())
		except:
			pass
		print "params",params
		if user and (user.email() not in ["vincenzo.minolfi@gmail.com", "albi.mori@gmail.com", "mc3infotest@gmail.com", "test@example.com"]):
			print user.email(),"showLavoriInCorso"
			self.showLavoriInCorso(user)
			return
		if self.needAuth():
			if user:
				return method(user, **params)
			elif self.redirectToLogin():
				self.redirect(users.create_login_url(self.request.uri))
			else:
				self.response.out.write('{"error":"Utente non loggato!", "errorCode":440}')
		else:
			#print "Request parameters: ", self.getAllParametersGETInDict()
			return method(user, **params)

	def get(self):
		self.safeMethod(self.safeGet)

	def post(self):
		self.safeMethod(self.safePost)

	def put(self):
		self.safeMethod(self.safePut)

	def delete(self):
		self.safeMethod(self.safeDelete)
	
	def safeGet(self, user, **params):
		self.response.out.write("<div class='error'>safeGet va reimplementato dagli handler ereditanti!</div>")

	def safePost(self, user, **params):
		self.response.out.write("<div class='error'>safePost va reimplementato dagli handler ereditanti!</div>")

	def safePut(self, user, **params):
		self.response.out.write("<div class='error'>safePut va reimplementato dagli handler ereditanti!</div>")

	def safeDelete(self, user, **params):
		self.response.out.write("<div class='error'>safeDelete va reimplementato dagli handler ereditanti!</div>")
	
	def showLavoriInCorso(self, user):
		template_values = {
			'datetime':datetime.datetime.utcnow().strftime("%d/%m/%y %X"),
			'usermail':user.email(),
			'username':user.nickname(),
			'logsession':users.create_logout_url('/')
		}
		path = "html/underconstruction.html"
		path = os.path.join(os.path.dirname(__file__), path)
		self.response.out.write(template.render(path, template_values))
		return
		
	def getAllParametersGETInDict(self):
		dic = dict()

		for argkey in self.request.arguments():
			dic[argkey] = self.request.get(argkey)
			if dic[argkey]=="true": dic[argkey] = True
			if dic[argkey]=="false": dic[argkey] = False
		return dic

	def getAllParametersPOSTInDict(self):
		try:
			return json.loads(self.request.body)
		except:
			return {}
	
	def sendError(self, e, msg=None, data=None):
		self.response.out.write(json.dumps({
			'status': hasattr(e, 'code') and e.code or -1,
			'resultType':'error',
			'msg': msg or str(e),
			'data':data
		}, default=lambda o: o.__dict__))







class JSONHandler(MyHandler):

	# def get(self):
	# 	raise NoMethodException("get")

	# def post(self):
	# 	raise NoMethodException("post")

	# def delete(self):
	# 	raise NoMethodException("delete")

	# def put(self):
	# 	raise NoMethodException("put")

	#params.update(self.getAllParametersPOSTInDict())
	def get(self):
		print "--get--"
		params = self.getAllParametersGETInDict()
		path = self.request.path_info[1:].split("/")
		if len(path)>1:
			params["small"] = path[1]=="small"
		self.safeMethod(self.safeGet, params)

	def post(self):
		print "--post--"
		params = self.getAllParametersPOSTInDict()
		self.safeMethod(self.safePost, params)

	def delete(self):
		print "---delete---"
		path = self.request.path_info[1:].split("/")
		#if not len(path)>1:
		#	raise InexistentKeyException
		params = {}
		if len(path)>1:
			params = { "key": path[1] }
		self.safeMethod(self.safeDelete, params)

	def put(self):
		print "---put---"
		params = self.getAllParametersPOSTInDict()
		#key = self.request.path_info[1:].split("/")[1]
		self.safeMethod(self.safePut, params)

	
	def safeMethod(self, method, params):
		try:
			user = users.get_current_user()
			if not user:
				raise NoUserException()

			data = method(user, **params)
			#print "data",data
			
			self.response.headers['Content-Type'] = 'application/json'
			self.response.out.write(json.dumps({
				"status":0,
				"resultType":"",
				"msg":"",
				"data":data
			}))
		except MyException as me:
			self.response.headers['Content-Type'] = 'application/json'
			self.response.out.write(json.dumps({
				"status":me.code,
				"resultType":"",
				"msg":me.value,
				"data": me.data
			}))
		except Exception as ex:
			print "BUG",ex
			self.response.headers['Content-Type'] = 'application/json'
			self.response.out.write(json.dumps({
				"status":-2,
				"resultType":"",
				"msg":"Bug! Controllare il log del server",
				"data":None
			}))



